Popular Searches
Popular Course Categories
Popular Courses

Introduction to REST APIs and HTTP Methods

Introduction to REST APIs and HTTP Methods

API Integration and Network Requests

Introduction to REST APIs and HTTP Methods in React Native

Course: React Native Training

Topic: Introduction to REST APIs and HTTP Methods

Course Link: React Native Training Course

Demo Link: Register for a Course Demo

Academy Website: JustAcademy


1. Introduction to REST APIs

REST APIs are an important part of modern mobile application development. They allow applications built with React Native to communicate with backend servers, retrieve information, submit user data, and perform operations on remote resources.

For example, a shopping application may use a REST API to display products, add items to a cart, create orders, and retrieve order history. A social media application may use APIs to load profiles, publish posts, and retrieve comments.

REST stands for Representational State Transfer. It is an architectural style used to design network-based services. An API, or Application Programming Interface, defines how one software application communicates with another.

1.1 What Is a REST API?

A REST API exposes resources through URLs and uses HTTP methods to describe the operations a client wants to perform on those resources.

For example, an online store might provide the following endpoints:

  • GET /products — retrieve a list of products.
  • GET /products/10 — retrieve product 10.
  • POST /products — submit a request to create a product.
  • PUT /products/10 — replace the representation of product 10.
  • PATCH /products/10 — update selected fields of product 10.
  • DELETE /products/10 — request deletion of product 10.

The exact endpoints and supported methods depend on the backend API. These examples illustrate common REST API conventions.

1.2 Why REST APIs Are Used

  • They allow mobile applications to access server-side information.
  • They separate the user interface from backend business logic.
  • They allow multiple clients to use the same backend services.
  • They support operations such as retrieving, creating, updating, and deleting resources.
  • They can return structured data in formats such as JSON.
  • They make it easier to integrate authentication, payments, notifications, and other services.
  • They support communication between independently developed applications and services.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Explain REST APIs and their role in React Native development.
  • Understand client-server communication.
  • Identify resources, endpoints, URLs, and request parameters.
  • Understand HTTP requests and responses.
  • Use GET, POST, PUT, PATCH, and DELETE methods.
  • Understand HTTP headers, request bodies, and JSON data.
  • Send API requests using the Fetch API.
  • Interpret common HTTP status codes.
  • Handle API errors and loading states.
  • Apply basic security and API integration best practices.

3. Understanding Client-Server Architecture

REST APIs commonly operate using a client-server architecture. The client sends a request, and the server processes it and returns a response.

3.1 The Client

The client is the application that requests information or asks the server to perform an operation. In React Native development, the client is the mobile application running on a user's device.

Examples of client responsibilities include:

  • Displaying forms and buttons.
  • Collecting user input.
  • Sending HTTP requests.
  • Displaying the information returned by the server.
  • Showing loading indicators and error messages.

3.2 The Server

The server receives API requests, applies business rules, interacts with databases or other services, and sends responses back to the client.

For example, when a user signs in, the server validates the supplied credentials and returns an appropriate response. The server should perform the actual authentication rather than relying only on client-side checks.

3.3 Database

A database stores application information such as users, products, orders, and messages. The backend server commonly communicates with the database and exposes the required information through API endpoints.

3.4 Client-Server Request Flow

  1. The user opens a screen in the React Native application.
  2. The application creates an HTTP request.
  3. The request is sent to the backend API.
  4. The server validates the request and processes the operation.
  5. The server may retrieve or modify information in a database.
  6. The server returns an HTTP response.
  7. The React Native application checks the response and updates its interface.

4. Understanding REST Principles

REST is an architectural style with several principles that guide API design. Not every HTTP API follows every REST constraint, so it is useful to understand these concepts when working with APIs.

4.1 Client-Server Separation

The client interface and server-side data management are separated. The mobile application focuses on user interaction, while the backend manages data and business logic.

4.2 Stateless Communication

In REST, each request should contain the information needed to understand and process it. The server should not depend on conversational state stored from a previous request to interpret the current request.

For example, an authenticated request may include an access token in its authorization header. The server can use the token to identify and authorize the request.

4.3 Cacheability

Responses can indicate whether they may be cached. Suitable caching can reduce unnecessary requests and improve performance. Sensitive or frequently changing data requires careful caching rules.

4.4 Uniform Interface

Resources are identified through consistent URLs, and standard HTTP methods describe the intended operation. Consistent API conventions make endpoints easier to understand and maintain.

4.5 Layered System

A client may communicate with a server through intermediaries such as gateways, reverse proxies, or caches. These layers can support security, routing, and performance without requiring the client to know every internal detail.

5. Understanding Resources and Endpoints

A resource represents an item or collection of information managed by an API. Examples include users, products, orders, comments, and categories.

5.1 What Is a Resource?

A resource is the information that an API makes available for operations. For example, a product resource may contain an ID, name, price, description, and category.

{
  "id": 10,
  "name": "Wireless Headphones",
  "price": 2499,
  "category": "Electronics"
}

5.2 What Is an Endpoint?

An endpoint is a URL or route through which an API exposes a particular resource or operation.

Endpoint Purpose
/users Access the users collection.
/users/5 Access a particular user.
/products Access the products collection.
/products/10 Access a particular product.
/orders Access order resources.

5.3 Base URL and Full URL

The base URL identifies the API host, while the endpoint path identifies a resource or operation within the API.

Base URL:
https://api.example.com/v1

Endpoint:
/products

Full URL:
https://api.example.com/v1/products

The domain and path above are illustrative. Replace them with the real API address and routes provided by your backend.

6. Introduction to HTTP

HTTP stands for Hypertext Transfer Protocol. It defines how clients and servers exchange requests and responses. REST APIs commonly use HTTP or HTTPS to communicate.

6.1 HTTP Request

An HTTP request usually contains a method, a URL or path, headers, and sometimes a request body.

Example request:

GET /products/10 HTTP/1.1
Host: api.example.com
Accept: application/json

6.2 HTTP Response

An HTTP response contains a status code, headers, and optionally a response body.

Example response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "id": 10,
  "name": "Wireless Headphones",
  "price": 2499
}

6.3 HTTP vs HTTPS

HTTP HTTPS
Communication is not encrypted by HTTP itself. HTTP is protected by TLS encryption.
Does not provide TLS-based server identity verification. Supports certificate-based server authentication.
Not suitable for transmitting sensitive data over an untrusted network without additional protection. Recommended for API communication, including authentication and personal data.

Use HTTPS for production API communication, particularly when requests contain authentication credentials or personal information.

7. Introduction to HTTP Methods

HTTP methods describe the intended action of a request. Selecting the appropriate method makes an API easier to understand and helps clients and servers apply consistent behavior.

The most common methods used in React Native API integration are GET, POST, PUT, PATCH, and DELETE. HTTP also defines methods such as HEAD and OPTIONS.

7.1 HTTP Methods Overview

Method Purpose Typical Use Case
GET Retrieve a resource. Load a list of products.
POST Submit data for processing or resource creation. Register a user or create an order.
PUT Replace a resource representation. Replace a user's profile information.
PATCH Apply a partial modification. Change a user's display name.
DELETE Request resource deletion. Delete a saved address.
HEAD Retrieve response headers without a response body. Check resource metadata.
OPTIONS Discover communication options supported by a resource. Check permitted methods or handle CORS preflight in browser-based environments.

8. GET Method

The GET method requests information from a server. It is normally used to read data and should not be used to request a change to the server's application state.

8.1 Common Uses of GET

  • Retrieve all products.
  • Fetch a particular user's profile.
  • Display order history.
  • Load categories and dashboard statistics.
  • Search for records using query parameters.

8.2 GET Request Example

GET https://api.example.com/v1/products

Example response:

[
  {
    "id": 1,
    "name": "Keyboard",
    "price": 999
  },
  {
    "id": 2,
    "name": "Mouse",
    "price": 499
  }
]

8.3 Fetching Data in React Native

async function getProducts() {
  const response = await fetch(
    'https://api.example.com/v1/products'
  );

  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }

  const products = await response.json();
  return products;
}

This function sends a GET request and returns the parsed response. Replace the example endpoint with a real products API.

9. POST Method

The POST method submits data to a server for processing. It is commonly used to create a resource or trigger an operation, depending on the API's design.

9.1 Common Uses of POST

  • Register a new user.
  • Submit a contact form.
  • Create a new order.
  • Send a comment or message.
  • Submit login credentials to an authentication endpoint.

9.2 POST Request Example

POST https://api.example.com/v1/products
Content-Type: application/json

{
  "name": "Keyboard",
  "price": 999
}

9.3 POST Request Using Fetch

async function createProduct() {
  const response = await fetch(
    'https://api.example.com/v1/products',
    {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: 'Keyboard',
        price: 999,
      }),
    }
  );

  if (!response.ok) {
    throw new Error(`Create failed: ${response.status}`);
  }

  return response.json();
}

The method option specifies POST. The Content-Type header tells the server that the request body contains JSON, and JSON.stringify() converts a JavaScript object into a JSON string.

The API may return a created resource, a status message, or no response body. Check the backend's contract before assuming that every successful POST response contains JSON.

10. PUT Method

The PUT method requests that the target resource be created or replaced with the representation provided by the request, according to the API's design. It is commonly used for a full resource update.

10.1 Example Use Case

Suppose a user profile contains a name, email address, and phone number. A PUT endpoint may expect the complete representation required by the API.

PUT https://api.example.com/v1/users/5
Content-Type: application/json

{
  "name": "Aarav Sharma",
  "email": "[email protected]",
  "phone": "9876543210"
}

10.2 PUT Request Using Fetch

async function replaceUser() {
  const response = await fetch(
    'https://api.example.com/v1/users/5',
    {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        name: 'Aarav Sharma',
        email: '[email protected]',
        phone: '9876543210',
      }),
    }
  );

  if (!response.ok) {
    throw new Error(`Update failed: ${response.status}`);
  }

  if (response.status === 204) {
    return null;
  }

  return response.json();
}

This example handles a possible 204 No Content response. The required fields and exact behavior depend on the backend API.

11. PATCH Method

The PATCH method requests a partial modification of a resource. Instead of sending every field, the client sends the changes supported by the endpoint.

11.1 Example Use Case

If a user wants to change only their display name, the API may accept a request containing that single field.

PATCH https://api.example.com/v1/users/5
Content-Type: application/json

{
  "name": "Aarav S."
}

11.2 PATCH Request Using Fetch

async function updateUserName() {
  const response = await fetch(
    'https://api.example.com/v1/users/5',
    {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        name: 'Aarav S.',
      }),
    }
  );

  if (!response.ok) {
    throw new Error(`Partial update failed: ${response.status}`);
  }

  if (response.status === 204) {
    return null;
  }

  return response.json();
}

PATCH behavior depends on the server's implementation and the patch format it supports. Do not assume every PATCH endpoint accepts the same request body format.

12. DELETE Method

The DELETE method requests removal of a resource. The server determines whether the caller is authorized and whether the resource can be deleted.

12.1 Example Use Case

A shopping application may let users remove a saved address or delete a record they own.

DELETE https://api.example.com/v1/products/10

12.2 DELETE Request Using Fetch

async function deleteProduct(productId) {
  const response = await fetch(
    `https://api.example.com/v1/products/${productId}`,
    {
      method: 'DELETE',
    }
  );

  if (!response.ok) {
    throw new Error(`Delete failed: ${response.status}`);
  }

  return true;
}

Many DELETE endpoints return 204 No Content, while others return a JSON confirmation. Do not automatically call response.json() unless the endpoint returns a JSON body.

13. PUT vs PATCH

PUT PATCH
Typically replaces the resource representation. Applies partial changes to a resource.
Often expects the complete representation defined by the endpoint. Often accepts only the fields that need to change.
Defined as idempotent by HTTP semantics. Not guaranteed to be idempotent; behavior depends on the patch operation.
Example: replace the supported profile fields. Example: update only the profile name.

14. Safe and Idempotent HTTP Methods

Two important HTTP concepts are safety and idempotency. They help developers understand how a method is intended to behave when requests are repeated.

14.1 Safe Methods

A safe method is intended to read information without requesting a change to the server's application state. GET, HEAD, and OPTIONS are examples of safe methods.

14.2 Idempotent Methods

A method is idempotent when making the same request multiple times has the same intended effect on the server as making it once. This does not require every response to be identical.

For example, setting a user's profile to the same representation using PUT should result in the same intended resource state even if the request is repeated.

14.3 Method Comparison

Method Safe? Idempotent?
GET Yes Yes
HEAD Yes Yes
OPTIONS Yes Yes
POST No Not guaranteed
PUT No Yes
PATCH No Not guaranteed
DELETE No Yes, by HTTP semantics

Idempotency describes intended effects, not identical status codes or response bodies. For operations such as payments and order creation, use backend-supported idempotency mechanisms where appropriate to prevent duplicate actions.

15. Understanding Query Parameters and Path Parameters

APIs often use path parameters and query parameters to identify resources or filter the results returned by an endpoint.

15.1 Path Parameters

Path parameters identify a particular resource or a position in a resource hierarchy.

GET /products/10
GET /users/5/orders

In these examples, 10 identifies a product and 5 identifies a user.

15.2 Query Parameters

Query parameters appear after a question mark in a URL. They are commonly used for searching, filtering, sorting, and pagination.

GET /products?category=electronics
GET /products?sort=price
GET /products?page=2&limit=10
GET /users?search=aarav

15.3 Query Parameters in React Native

const url = new URL('https://api.example.com/v1/products');

url.searchParams.set('category', 'electronics');
url.searchParams.set('page', '2');
url.searchParams.set('limit', '10');

const response = await fetch(url.toString());

For an environment where the URL API is unavailable or unsuitable, query strings can also be assembled with a URL-encoding utility. Always encode user-provided search terms and other dynamic values correctly.

16. Understanding HTTP Headers

HTTP headers provide additional information about a request or response. They can describe content formats, authentication, caching, and other communication details.

16.1 Common Request Headers

Header Purpose
Accept Indicates the response media types the client can accept.
Content-Type Describes the media type of the request body.
Authorization Carries credentials or a token using the scheme supported by the API.
Cache-Control Provides caching directives.
If-Match Can be used for conditional requests based on an entity tag.

16.2 Sending Headers with Fetch

const response = await fetch(
  'https://api.example.com/v1/profile',
  {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      Authorization: `Bearer ${accessToken}`,
    },
  }
);

The accessToken variable must come from the application's legitimate authentication flow. Do not hardcode real access tokens in source code or commit them to a repository.

17. Understanding JSON Data

JSON stands for JavaScript Object Notation. It is a common data-interchange format used by REST APIs because it is compact, readable, and supported by many programming languages.

17.1 JSON Object

{
  "id": 101,
  "name": "Wireless Mouse",
  "price": 799,
  "inStock": true
}

17.2 JSON Array

[
  {
    "id": 1,
    "name": "Keyboard"
  },
  {
    "id": 2,
    "name": "Mouse"
  }
]

17.3 Converting JSON in React Native

const response = await fetch(
  'https://api.example.com/v1/products'
);

if (!response.ok) {
  throw new Error('Unable to load products.');
}

const products = await response.json();

The response.json() method reads and parses the response body. It returns a Promise, so it is commonly used with await.

18. Understanding HTTP Status Codes

An HTTP status code indicates the result of a request. React Native applications should use the status code to decide how to handle a response.

18.1 Successful Responses

Status Meaning Typical Use
200 OK The request succeeded. Data was retrieved or an operation completed.
201 Created A resource was created. A new record was successfully created.
202 Accepted The request was accepted for processing. A background task may continue processing.
204 No Content The request succeeded without a response body. A successful update or deletion.

18.2 Client Errors

Status Meaning Typical Handling
400 Bad Request The request is invalid or cannot be processed as submitted. Review parameters or submitted fields.
401 Unauthorized Valid authentication credentials are missing or unacceptable. Check authentication or ask the user to sign in again.
403 Forbidden The server refuses the operation. Explain that the user does not have permission.
404 Not Found The requested resource was not found. Show a missing-resource message.
409 Conflict The request conflicts with the current resource state. Explain the conflict or refresh the data.
422 Unprocessable Content The server cannot process the submitted content under its validation rules. Display appropriate validation feedback.
429 Too Many Requests The request rate limit was exceeded. Respect rate limits and any Retry-After guidance.

18.3 Server Errors

Status Meaning Typical Handling
500 Internal Server Error The server encountered an unexpected problem. Show a general error message.
502 Bad Gateway A gateway received an invalid response from an upstream server. Offer retry when appropriate.
503 Service Unavailable The service is temporarily unable to handle the request. Try again later, respecting retry guidance.
504 Gateway Timeout A gateway did not receive a timely upstream response. Inform the user and offer retry when appropriate.

19. Integrating REST APIs in React Native

React Native applications can use the JavaScript Fetch API to communicate with REST endpoints. API requests are often performed inside event handlers or React effects, depending on when the data is needed.

19.1 Fetch API Overview

The Fetch API allows a client to send HTTP requests and receive a Response object.

const response = await fetch(
  'https://jsonplaceholder.typicode.com/users'
);

if (!response.ok) {
  throw new Error(`HTTP error: ${response.status}`);
}

const users = await response.json();

The example uses a public demonstration endpoint. Use a real backend URL when building your own application.

19.2 Fetching Data with useEffect

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, Text, View } from 'react-native';

export default function UsersScreen() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function loadUsers() {
      try {
        const response = await fetch(
          'https://jsonplaceholder.typicode.com/users'
        );

        if (!response.ok) {
          throw new Error('Unable to fetch users.');
        }

        const result = await response.json();
        setUsers(result);
      } catch (err) {
        setError('Could not load users. Please try again.');
      } finally {
        setLoading(false);
      }
    }

    loadUsers();
  }, []);

  if (loading) {
    return (
      <View>
        <ActivityIndicator size="large" />
        <Text>Loading users...</Text>
      </View>
    );
  }

  if (error) {
    return <Text>{error}</Text>;
  }

  return (
    <View>
      {users.map(user => (
        <Text key={user.id}>{user.name}</Text>
      ))}
    </View>
  );
}

This example introduces API integration, but a production screen should also consider request cancellation, retry behavior, empty results, and efficient list rendering with FlatList for larger collections.

20. Creating and Updating Resources from React Native

API integration is not limited to retrieving data. Applications often need to send form data, update records, and delete resources.

20.1 Sending Form Data with POST

async function submitContactForm(name, email, message) {
  const response = await fetch(
    'https://api.example.com/v1/contact',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        name,
        email,
        message,
      }),
    }
  );

  if (!response.ok) {
    throw new Error('Unable to submit the contact form.');
  }

  return response.json();
}

The form values should be validated before submission. The server must also validate them because client-side validation alone is not a security boundary.

20.2 Updating a Resource with PATCH

async function updateProfileName(userId, name) {
  const response = await fetch(
    `https://api.example.com/v1/users/${userId}`,
    {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name }),
    }
  );

  if (!response.ok) {
    throw new Error('Unable to update profile.');
  }

  if (response.status === 204) {
    return null;
  }

  return response.json();
}

20.3 Deleting a Resource

async function removeAddress(addressId) {
  const response = await fetch(
    `https://api.example.com/v1/addresses/${addressId}`,
    {
      method: 'DELETE',
    }
  );

  if (!response.ok) {
    throw new Error('Unable to delete address.');
  }
}

After a successful deletion, update the screen or refetch the relevant data. For destructive operations, provide suitable confirmation and ensure that the server authorizes the action.

21. Error Handling in REST API Integration

API requests can fail because of connectivity issues, invalid input, authentication problems, server errors, or unexpected response formats. A robust application handles these conditions without crashing.

21.1 Handling HTTP Errors

async function fetchProducts() {
  const response = await fetch(
    'https://api.example.com/v1/products'
  );

  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }

  return response.json();
}

21.2 Using try/catch/finally

try {
  setLoading(true);
  setError(null);

  const products = await fetchProducts();
  setProducts(products);
} catch (error) {
  setError('Unable to load products.');
} finally {
  setLoading(false);
}

The finally block allows the application to stop showing the loading indicator after the request settles. The UI should distinguish between an initial loading failure and a refresh failure when previous data is already available.

21.3 Common API Errors

  • Incorrect endpoint URL.
  • Missing or invalid authorization credentials.
  • Invalid JSON request body.
  • Incorrect HTTP method.
  • Missing required parameters.
  • Server-side validation failures.
  • Network connectivity problems.
  • Unexpected or empty response bodies.

22. Authentication and Authorization

Many REST APIs protect private resources with authentication and authorization.

22.1 Authentication

Authentication establishes who the user or client is. An API may use access tokens, session cookies, or another supported authentication mechanism.

22.2 Authorization

Authorization determines what an authenticated user is allowed to do. For example, a user may view their own orders but may not delete another user's order.

22.3 Bearer Token Example

const response = await fetch(
  'https://api.example.com/v1/profile',
  {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      Authorization: `Bearer ${accessToken}`,
    },
  }
);

Use the token format specified by the API. Store credentials using an appropriate secure storage solution, do not include secrets directly in source code, and never rely on client-side checks alone to enforce permissions.

23. REST API Testing Tools

Testing an API before integrating it into React Native can help identify incorrect routes, headers, request bodies, and authentication settings.

Tool Purpose
Postman Create and send HTTP requests, inspect responses, and organize API collections.
Insomnia Test and organize API requests.
cURL Send HTTP requests from a command line.
Browser developer tools Inspect network requests in supported browser-based environments.
React Native debugging tools Help inspect application behavior and troubleshoot integration issues.

23.1 Testing a GET Request with cURL

curl -i https://jsonplaceholder.typicode.com/users

23.2 Testing a POST Request with cURL

curl -X POST https://api.example.com/v1/products \
  -H "Content-Type: application/json" \
  -d '{"name":"Keyboard","price":999}'

Replace the example endpoint with an actual API that supports the operation. Use test data and avoid putting real passwords or access tokens in shared terminal history.

24. Common Problems and Troubleshooting

Problem Possible Cause Solution
Request returns 404. Incorrect URL or missing resource. Verify the endpoint and resource ID.
Request returns 401. Missing, expired, or invalid authentication. Check the authentication flow and token.
Request returns 403. The user lacks permission. Check the user's authorization and server rules.
Request returns 500. Server-side error. Inspect server logs and show a user-friendly message.
POST request fails. Incorrect body, missing headers, or validation failure. Verify Content-Type, JSON structure, and required fields.
JSON parsing fails. The response is empty or is not valid JSON. Inspect the response and handle bodyless success responses.
Data is not displayed. Incorrect state update or unexpected data structure. Inspect the response and validate its shape.
Request fails on a device. Connectivity, certificate, host, or environment configuration issue. Verify device connectivity and server configuration.
Duplicate records are created. Repeated POST requests or duplicate submissions. Prevent accidental repeat submissions and use backend idempotency protections where appropriate.
App displays sensitive error details. Raw server errors are shown directly. Show safe, user-friendly messages and log details securely.

25. REST API Security Best Practices

  • Use HTTPS for production API requests.
  • Never store private server secrets inside a mobile app bundle.
  • Use secure storage for authentication tokens when appropriate.
  • Validate all important inputs on the server.
  • Enforce authentication and authorization on protected endpoints.
  • Avoid logging passwords, tokens, and sensitive personal data.
  • Handle expired tokens and authentication errors safely.
  • Use rate limiting and abuse protections on the backend.
  • Follow the API's retry and idempotency rules.
  • Keep user-facing error messages clear without exposing internal implementation details.

26. Best Practices for REST API Design

  • Use resource-oriented endpoint names, such as /products and /orders.
  • Use HTTP methods consistently with their intended semantics.
  • Return meaningful HTTP status codes.
  • Use a consistent response structure where practical.
  • Validate request data and return useful validation errors.
  • Document required fields, supported methods, and response formats.
  • Support pagination for large collections.
  • Use appropriate caching headers for cacheable data.
  • Version APIs when changes may break existing clients.
  • Protect sensitive resources with server-side authentication and authorization.

27. Practical Project: Product Management App

Project Objective: Build a React Native application that integrates with a REST API to list, create, update, and delete products.

27.1 Project Features

  • Display a list of products using GET.
  • Display product details using a resource ID.
  • Create a product using POST.
  • Replace product information using PUT where supported.
  • Update selected product fields using PATCH where supported.
  • Delete a product using DELETE.
  • Show loading indicators during requests.
  • Display appropriate success and error messages.
  • Validate form inputs before submitting them.
  • Refresh or update the list after successful changes.

27.2 Development Steps

  1. Set up a React Native project.
  2. Select a test API or create a backend with the required endpoints.
  3. Test each endpoint using Postman or cURL.
  4. Create a Products screen and a reusable ProductCard component.
  5. Implement the GET request and display the returned data.
  6. Create a product form that submits a POST request.
  7. Implement update functionality using the method supported by the backend.
  8. Add a delete action with suitable confirmation.
  9. Handle HTTP errors and loading states.
  10. Test successful requests, invalid input, empty results, and network failures.

27.3 Expected Outcome

The application should allow users to interact with product resources through the API. The screen should display the latest available data and communicate the outcome of each operation clearly. The backend must enforce data validation and permissions.

28. Practice Exercises

  1. Explain REST APIs and describe how a React Native app communicates with a backend.
  2. Write a GET request to retrieve a list of users.
  3. Write a POST request that submits a name and email address.
  4. Demonstrate the difference between PUT and PATCH.
  5. Write a DELETE request for a product ID.
  6. Explain the purpose of Content-Type and Accept headers.
  7. Handle a 404 response without crashing the application.
  8. Parse a JSON response and display the data in a FlatList.
  9. Send an authenticated GET request using a bearer token.
  10. Test an API endpoint using Postman or cURL and record the status code.

29. Interview Questions and Answers

Q1. What is a REST API?

A REST API is an API designed around REST architectural principles. It commonly exposes resources through URLs and uses HTTP methods to interact with those resources.

Q2. What is the full form of REST?

REST stands for Representational State Transfer.

Q3. What is an endpoint?

An endpoint is a URL or route through which a client accesses a resource or performs an API operation.

Q4. What is HTTP?

HTTP is a protocol that defines how clients and servers exchange requests and responses.

Q5. What is the difference between GET and POST?

GET is intended to retrieve a resource representation, while POST submits data for processing or resource creation according to the endpoint's design.

Q6. What is the difference between PUT and PATCH?

PUT generally replaces a resource representation, whereas PATCH applies partial modifications. The exact request body depends on the API contract.

Q7. What does DELETE do?

DELETE requests removal of a specified resource. The server decides whether the operation is authorized and supported.

Q8. What is JSON?

JSON is a text-based data format commonly used to exchange structured information between clients and servers.

Q9. What is the purpose of an HTTP status code?

A status code communicates the result of a request, such as success, client error, or server error.

Q10. What does status code 200 mean?

200 OK indicates that the request succeeded.

Q11. What is the difference between 401 and 403?

401 indicates that valid authentication credentials are missing or unacceptable. 403 indicates that the server refuses the operation, often because the client lacks permission.

Q12. Why is HTTPS important?

HTTPS protects HTTP communication using TLS, helping protect data in transit and authenticate the server.

Q13. What is an HTTP header?

A header carries additional information about a request or response, such as the content type or authentication credentials.

Q14. Why do we use JSON.stringify() in a POST request?

It converts a JavaScript value into a JSON string suitable for sending as a JSON request body.

Q15. Why should response.ok be checked when using Fetch?

Fetch normally resolves for HTTP error responses such as 404 or 500. Checking response.ok lets the application detect unsuccessful HTTP status codes.

Q16. What is an idempotent method?

An idempotent method has the same intended server-side effect when the same request is repeated. PUT and DELETE are idempotent by HTTP semantics, although their responses may differ.

Q17. What is a query parameter?

A query parameter is a value supplied in the URL's query string, often used for filtering, searching, sorting, or pagination.

Q18. How can a React Native app handle API errors?

It can check response status codes, catch network and parsing errors, update error state, and display clear feedback with a retry option where appropriate.

30. Quick Revision Notes

  • REST: Architectural style for designing network-based services.
  • API: Interface through which software systems communicate.
  • Endpoint: URL or route for a resource or operation.
  • HTTP: Protocol for request-response communication.
  • GET: Retrieve a resource representation.
  • POST: Submit data for processing or resource creation.
  • PUT: Replace a resource representation.
  • PATCH: Apply partial changes.
  • DELETE: Request resource deletion.
  • Headers: Additional request or response information.
  • JSON: Common format for exchanging structured data.
  • 200: Successful request.
  • 201: Resource created.
  • 204: Successful response without a body.
  • 400: Bad request.
  • 401: Authentication credentials missing or unacceptable.
  • 403: Request refused, often because of insufficient permission.
  • 404: Resource not found.
  • 500: Internal server error.
  • HTTPS: HTTP communication protected by TLS.

31. Conclusion

REST APIs and HTTP methods are essential concepts for developing React Native applications that communicate with backend services. Understanding resources, endpoints, request bodies, headers, response codes, and method semantics allows developers to build applications that retrieve, create, update, and delete data correctly.

Begin by practising GET and POST requests, then learn PUT, PATCH, and DELETE. Test endpoints independently, validate server responses, handle loading and error states, and follow security best practices when working with authentication and personal information.

For further learning, explore the React Native Training Course, register through the JustAcademy course demo page, and visit the JustAcademy website.

32. Additional Learning Resources

whatsapp